package com.wt.struggle.goodbye.base

import android.app.Activity
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.graphics.BitmapFactory
import android.graphics.Typeface
import android.media.MediaPlayer
import android.net.Uri
import android.os.*
import android.provider.Settings
import android.support.design.widget.TabLayout
import android.support.v4.content.FileProvider
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.SearchView
import android.text.TextUtils
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.*
import butterknife.Unbinder
import com.google.gson.Gson
import com.wt.struggle.goodbye.App
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.user.activity.LoginActivity
import com.xin.lv.yang.utils.utils.ImageUtil
import com.xin.lv.yang.utils.view.CustomProgressDialog
import org.devio.takephoto.app.TakePhotoFragment
import org.json.JSONObject
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.lang.ref.WeakReference
import java.lang.reflect.Field

abstract class ProV4Fragment : TakePhotoFragment() {

    open var gson: Gson? = null
    var unbinder: Unbinder? = null
    var activity: Activity? = null

    var uid: Int = 0
    var token: String = ""
    var handler: Handler? = null

    var player: MediaPlayer? = null
    var send: Send? = null
    var inPutManager: InputMethodManager? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activity = getActivity()

        handler = ProHandler(this)
        gson = Gson()
        send = Send(activity!!)

        token = Share.getToken(activity!!)
        uid = Share.getId(activity!!)

        inPutManager = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

    }


    abstract fun handler(what: Int, arg1: Int, netInfo: NetInfo)


    private val ERROR = 404
    private val ERROR_BUG = 405

    companion object {

        class ProHandler(proV4Fragment: ProV4Fragment) : Handler(Looper.getMainLooper()) {

            var weak: WeakReference<ProV4Fragment>? = null

            init {
                weak = WeakReference(proV4Fragment)

            }

            val a = weak!!.get()

            override fun handleMessage(msg: Message?) {
                super.handleMessage(msg)
                when (msg!!.what) {
                    a!!.ERROR -> {
                        a.removeLoadDialog()
                        a.showToastShort(a.activity!!, "网络连接超时，请检查网络!")
                    }
                    a.ERROR_BUG -> {
                        a.removeLoadDialog()
                        a.showToastShort(a.activity!!, "提交失败，请稍后再试")
                    }

                    else -> {

                        val str = msg.obj as String

                        if (str != "") {
                            val json = JSONObject(str)
                            val jsonObject = json.optJSONObject("head")
                            val resultCode = jsonObject.optInt("response_status")
                            val resultMessage = jsonObject.optString("response_msg")

                            when (resultCode) {

                                Config.SUCCESS -> {
                                    val bodyResult = json.optString("body")

                                    val netInfo = NetInfo()
                                    netInfo.code = resultCode
                                    netInfo.dataResult = bodyResult
                                    netInfo.message = resultMessage

                                    a.handler(msg.what, msg.arg1, netInfo)

                                }

                                Config.NO_LOGIN -> {

                                    a.removeLoadDialog()
                                    Share.clear(a.activity!!)
                                    a.showToastShort(a.activity!!, resultMessage)
                                    a.startActivity(Intent(a.activity, LoginActivity::class.java))
                                }

                                else -> {

                                    val netInfo = NetInfo()
                                    netInfo.code = resultCode
                                    netInfo.dataResult = resultMessage

                                    a.handler(msg.what, msg.arg1, netInfo)

                                }
                            }
                        } else {
                            a.handler(msg.what, msg.arg1, NetInfo())
                        }
                    }
                }

            }
        }
    }


    fun reOpenApp() {
        /// 重启app
        val i: Intent =
            activity!!.baseContext.packageManager.getLaunchIntentForPackage(activity!!.baseContext.packageName)
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK)
        startActivity(i)
        App.exit()
    }


    /**
     * 播放语音文件
     */
    fun playVoice(context: Context, voiceUrl: String) {
        player = MediaPlayer()
        player!!.setDataSource(context, Uri.parse(voiceUrl))
        player!!.prepareAsync()
        player!!.setOnPreparedListener { mp ->
            mp.start()
        }
    }


    /**
     * 播放byte 二进制的音乐
     */
    fun playVoiceFromByte(context: Context, bb: ByteArray) {
        val tempMp3 = File.createTempFile("voice", "mp3", context.cacheDir)
        tempMp3.deleteOnExit()
        val fos = FileOutputStream(tempMp3)
        fos.write(bb)
        fos.close()

        val fis = FileInputStream(tempMp3)
        player!!.setDataSource(fis.fd)

        player!!.prepareAsync()
        player!!.setOnPreparedListener { mp ->
            mp.start()
        }

    }


    val isDebug: Boolean = true

    fun log(message: String) {
        if (isDebug) {
            Log.i("result", message)
        }

    }

    /**
     * 创建view
     */
    abstract fun createView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        val view = createView(inflater, container, savedInstanceState)

        return view
    }


    override fun onDestroy() {
        super.onDestroy()
        if (unbinder != null) {
            unbinder!!.unbind()
        }
    }


    /**
     * 改变tabLayout 字体大小和样式
     */
    fun changeTextStyle(textView: TextView, status: Boolean) {
        if (status) {
            textView.setTextColor(resources.getColor(R.color.black))
            textView.textSize = 20f
            textView.typeface = Typeface.DEFAULT_BOLD
        } else {
            textView.setTextColor(resources.getColor(R.color.black777))
            textView.textSize = 17f
            textView.typeface = Typeface.DEFAULT
        }
    }

    fun showShortToast(activity: Activity, str: String, time: Int = Toast.LENGTH_SHORT) {
        Toast.makeText(activity, str, time).show()
    }


    fun setAlpha(activity: Activity, f: Float) {
        val manager = activity.window.attributes
        manager.alpha = f
        activity.window.attributes = manager
    }

    fun showToastShort(context: Context, str: String) {
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show()
    }

    var customProgressDialog: CustomProgressDialog? = null

    fun showLoadDialog(context: Context, string: String = "加载中") {
        if (customProgressDialog == null) {
            customProgressDialog = CustomProgressDialog(context)
        }
        customProgressDialog!!.setText(string)
        customProgressDialog!!.show()

    }

    /**
     * 复制信息到剪切板
     */
    fun copy(context: Context, text: String) {
        val manager: ClipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        manager.text = text

    }

    /**
     * 移除load加载框
     */
    fun removeLoadDialog() {
        if (customProgressDialog != null) {
            if (customProgressDialog!!.isShowing) {
                customProgressDialog!!.dismiss()
            }
        }
    }


    fun setLine(searchView: SearchView, resId: Int) {
        try {
            val argClass = searchView.javaClass
            val ownField = argClass.getDeclaredField("mSearchPlate")
            ownField.isAccessible = true
            val mView = ownField.get(searchView) as View
            mView.setBackgroundColor(resId)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    var viewList: ArrayList<View>? = arrayListOf()

    /**
     * 顶部轮播图  1 为正常  2 为圆角
     */
    fun initViewPager(
        context: Context,
        picViewPager: ViewPager,
        radioGroup: RadioGroup?,
        picList: ArrayList<String>,
        handler: Handler,
        code: Int,
        backListener: OnImageBackListener?
    ) {

        if (radioGroup != null) {
            radioGroup.removeAllViews()
            for (i in 0 until picList.size) {
                val radioButton = RadioButton(context)
                radioButton.setButtonDrawable(R.drawable.point_check)
                radioButton.setPadding(8, 0, 0, 0)

                radioGroup.addView(radioButton)
            }
        }

        picViewPager.removeAllViews()
        viewList!!.clear()

        for (i in picList.indices) {
            val temp = picList[i]

            if (temp != null && temp != "" && temp != "null") {

                val view: View = LayoutInflater.from(context).inflate(R.layout.image_layout, null)

                val imageView: ImageView = view.findViewById(R.id.img_image_view)

                val w = getW(context as Activity)
                val bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.pic1)
                val bw = bitmap.width
                val bh = bitmap.height
                val h = w * bh / bw

                imageView.layoutParams = LinearLayout.LayoutParams(w, h)

                val picUrl = when {
                    temp.startsWith("http") -> temp
                    temp.startsWith("/") -> Config.IP + temp
                    else -> Config.GET_IMAGE_URL + temp
                }

                Log.i("result", "轮播图片-----" + picUrl)

                if (picUrl.startsWith("http")) {

                    if (code == 2) {
                        val r = context.resources.getDimension(R.dimen.dp_12).toInt()
                        ImageUtil.getInstance().loadRoundCircleImage(context, imageView, picUrl, 0, r)

                    } else {
                        ImageUtil.getInstance().loadImageNoTransformation(context, imageView, 0, picUrl)
                    }

                } else {

                    imageView.setImageBitmap(BitmapFactory.decodeResource(context.resources, picUrl.toInt()))
                }


                view.setOnClickListener {
                    if (backListener != null) {
                        backListener.onImageBack(i)
                    }
                }

                viewList!!.add(view)
            }
        }

        picViewPager.adapter = object : PagerAdapter() {
            override fun isViewFromObject(view: View, `object`: Any): Boolean {
                return view == `object`
            }

            override fun getCount(): Int = viewList!!.size


            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                container.removeView(viewList!![position])
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                val view: View? = viewList!![position]

                container.addView(view)

                return viewList!![position]
            }
        }

        initRunnable(handler, picViewPager, radioGroup)

        picViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                if (radioGroup != null) {
                    val rb = radioGroup.getChildAt(position) as RadioButton
                    rb.isChecked = true
                }

            }

            override fun onPageSelected(position: Int) {

            }

        })

    }


    var viewpagerRunnable: Runnable? = null;


    private val TIME: Long = 5 * 1000

    /**
     * 定时轮播
     */
    private fun initRunnable(handler: Handler, viewPager: ViewPager, radioGroup: RadioGroup?) {
        viewpagerRunnable = Runnable {
            val nowIndex = viewPager.currentItem
            val count = viewPager.adapter!!.count

            /// 如果下一张的索引大于最后一张，则切换到第一张
            if (nowIndex + 1 >= count) {
                viewPager.currentItem = 0

            } else {
                viewPager.currentItem = nowIndex + 1

            }

            handler.postDelayed(viewpagerRunnable, TIME)
        }

        handler.postDelayed(viewpagerRunnable, TIME)

        if (radioGroup != null) {
            val p = viewPager.currentItem
            val rb = radioGroup.getChildAt(p) as RadioButton
            rb.isChecked = true

        }

    }


    fun getW(activity: Activity): Int {
        val att = activity.windowManager.defaultDisplay
        return att.width
    }

    fun getH(activity: Activity): Int {
        val att = activity.windowManager.defaultDisplay
        return att.height
    }


    /**
     * 隐藏输入法
     */
    fun hideInPut(view: View) {
        if (inPutManager != null) {
            inPutManager!!.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }


    fun isLocationEnabled(context: Context): Boolean {
        var locationMode = 0
        var locationProviders = ""

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode =
                    Settings.Secure.getInt(context.contentResolver, Settings.Secure.LOCATION_MODE)

            } catch (e: Settings.SettingNotFoundException) {
                e.printStackTrace()
                return false
            }

            return locationMode != Settings.Secure.LOCATION_MODE_OFF;

        } else {
            locationProviders = Settings.Secure.getString(
                context.contentResolver,
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED
            )
            return !TextUtils.isEmpty(locationProviders);
        }

    }

    fun setIndicator(tabs: TabLayout, leftDip: Int, rightDip: Int) {
        val tabLayout = tabs.javaClass
        var tabStrip: Field? = null
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip")
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        }

        tabStrip!!.isAccessible = true
        var llTab: LinearLayout? = null
        try {
            llTab = tabStrip.get(tabs) as LinearLayout
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }

        val left = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            leftDip.toFloat(),
            Resources.getSystem().getDisplayMetrics()
        ).toInt()
        val right = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            rightDip.toFloat(),
            Resources.getSystem().getDisplayMetrics()
        ).toInt()

        for (i in 0 until llTab!!.childCount) {
            val child = llTab.getChildAt(i)
            child.setPadding(0, 0, 0, 0)
            val params = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f)
            params.leftMargin = left
            params.rightMargin = right
            child.layoutParams = params
            child.invalidate()
        }

    }


    fun buildUri(): Uri {

        val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
        if (!path.exists()) {
            path.mkdirs()
        }

        val name = System.currentTimeMillis().toString() + ".png"
        val file = File(path, name)

        if (!file.exists()) {
            file.createNewFile()
        }

        return Uri.fromFile(file)


    }

}